package com.treasure.mall.zbqmallapi.controller;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.google.common.collect.Lists;
import com.treasure.mall.biz.remote.quickpay.WechatPayService;
import com.treasure.mall.biz.service.core.order.AfterSaleService;
import com.treasure.mall.biz.service.core.pay.PayService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 
 * +---------------------------------------------------------
 * * @package: com.treasure.mall.zbqmallapi.controller
 * * @author: guomw (guomwchen@foxmail.com)
 * * @date: 2020/6/13 16:02
 * * @since: V1.0.0
 * +---------------------------------------------------------
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 * Copyright 2019-2022 com.treasure.mall.zbqmallapi.controller Inc. All rights reserved.
 */
@Slf4j
@RestController
@RequestMapping("/wxPay")
public class WechatNotifyController {

    private static final String REFUND_SUCCESS = "SUCCESS";
    @Resource
    private WechatPayService wechatPayService;
    @Resource
    private PayService payService;
    @Resource
    private AfterSaleService afterSaleService;

    /**
     * 微信订单支付通知
     *
     * @param xmlData
     * @return
     */
    @PostMapping("/notify/order")
    public String parseOrderNotifyResult(@RequestBody String xmlData) {
        try {
            WxPayService wxPayService = wechatPayService.getWxPayService();
            final WxPayOrderNotifyResult notifyResult = wxPayService.parseOrderNotifyResult(xmlData);
            //校验结果
            notifyResult.checkResult(wxPayService, "MD5", false);
            List<String> successStrings = Lists.newArrayList("SUCCESS", "");

            boolean isSuccess = successStrings.contains(StringUtils.trimToEmpty(notifyResult.getReturnCode()).toUpperCase())
                    || !successStrings.contains(StringUtils.trimToEmpty(notifyResult.getResultCode()).toUpperCase());

            //这里是存储我们发起支付时订单号的信息，所以取出来
            String paymentId = notifyResult.getOutTradeNo();
            //微信业务订单
            String tradeNo = notifyResult.getTransactionId();
            //支付成功回调通知
            payService.thirdPayed(paymentId, tradeNo, isSuccess, notifyResult.getReturnMsg());
            return WxPayNotifyResponse.success("成功");

        } catch (WxPayException wxEx) {
            log.error("wx_notify发生异常[payex]：" + wxEx.getMessage(), wxEx);
        } catch (Exception ex) {
            log.error("wx_notify发生异常：" + ex.getMessage(), ex);
        }
        return WxPayNotifyResponse.fail("失败");
    }

    /**
     * 微信退款通知
     *
     * @param xmlData
     * @return
     */
    @RequestMapping("/notify/refund")
    public String parseRefundNotifyResult(@RequestBody String xmlData) {
        try {
            WxPayService wxPayService = wechatPayService.getWxPayService();
            final WxPayRefundNotifyResult wxPayRefundNotifyResult = wxPayService.parseRefundNotifyResult(xmlData);
            if (REFUND_SUCCESS.equals(wxPayRefundNotifyResult.getReturnCode())) {
                WxPayRefundNotifyResult.ReqInfo reqInfo = wxPayRefundNotifyResult.getReqInfo();
                //判断退款状态
                boolean isSuccess = REFUND_SUCCESS.equals(reqInfo.getRefundStatus());
                /**
                 * 系统内部的退款单号
                 */
                String outRefundNo = reqInfo.getOutRefundNo();
                /**
                 * 系统内部的付款单号
                 */
                String outTradeNo = reqInfo.getOutTradeNo();
                /**
                 * 微信退款单号
                 */
                String refundId = reqInfo.getRefundId();
                /**
                 * 微信订单号
                 */
                String thirdTradingNo = reqInfo.getTransactionId();
                /**
                 * 一、可能会重复回调，需要做防重判断
                 * 二、处理我们系统内部业务，做修改订单状态，释放资源等！
                 */
                afterSaleService.complete(outRefundNo, refundId, isSuccess, wxPayRefundNotifyResult.getReturnMsg(), reqInfo.getRefundRecvAccout());
                if (isSuccess) {
                    return WxPayNotifyResponse.success("退款成功！");
                }
            }
        } catch (Exception ex) {
            log.error("wx_refund_notify发生异常：" + ex.getMessage(), ex);
        }
        return WxPayNotifyResponse.fail("退款失败");
    }


}
